package
{
    import flash.utils.ByteArray
    
    public class ExploitByteArray
    {
        private const MAX_STRING_LENGTH:uint = 100
        public var ba:ByteArray
        public var original_length:uint
        private var platform:String

        public function ExploitByteArray(p:String, l:uint = 1024)
        {
            ba = new ByteArray()
            ba.length = l
            ba.endian = "littleEndian"
            ba.writeUnsignedInt(0)
            platform = p
            original_length = l
        }

        public function set_length(length:uint):void
        {
            ba.length = length
        }

        public function get_length():uint
        {
            return ba.length
        }

        public function lets_ready():void
        {
            ba.endian = "littleEndian"
            if (platform == "linux") {
                ba.length = 0xffffffff
            } 
        }

        public function is_ready():Boolean
        {
            if (ba.length == 0xffffffff)
                return true

            return false
        }

        public function read(addr:uint, type:String = "dword"):uint
        {
            ba.position = addr
            switch(type) {
                case "dword": 
                    return ba.readUnsignedInt()
                case "word":
                    return ba.readUnsignedShort()
                case "byte":
                    return ba.readUnsignedByte()
            }
            return 0
        }

        public function read_string(addr:uint, length:uint = 0):String
        {
            ba.position = addr
            if (length == 0)
                return ba.readUTFBytes(MAX_STRING_LENGTH)
            else
                return ba.readUTFBytes(length) 
        }

        public function write(addr:uint, value:* = 0, zero:Boolean = true):void
        {
            var i:uint

            if (addr) ba.position = addr
            if (value is String) {
                for (i = 0; i < value.length; i++) ba.writeByte(value.charCodeAt(i))
                if (zero) ba.writeByte(0)
            } else if (value is ByteArray) {
                var value_length:uint = value.length
                for (i = 0; i < value_length; i++) ba.writeByte(value.readByte())
            } else ba.writeUnsignedInt(value)
        }
    }
}
